import {Component, OnInit} from '@angular/core';
import {Scheme} from '../../../../../entity/scheme.model';
import {BladeContainerInterface} from '../../../../../shared/blade/blade-container.interface';
import {Blade} from '../../../../../shared/blade/blade.model';
import {Observable} from 'rxjs/Observable';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {BladeContainerBase} from '../../../../../shared/blade/blade-container-base';
import {BladeData} from '../../../../../shared/blade/blade-data';
import {Command} from '../../../../../shared/toolbar.service';
import {SchemeService} from '../../../../../service/scheme.service';
import {ModelSchemeService} from '../../../../../service/model-scheme.service';

@Component({
  selector: 'app-fault-alarm-group-edit',
  templateUrl: './fault-alarm-group-edit.component.html',
  styleUrls: ['./fault-alarm-group-edit.component.css']
})
export class FaultAlarmGroupEditComponent extends BladeContainerBase<Scheme> {

  constructor(
    private fb: FormBuilder,
    private schemeService: SchemeService,
    private modelSchemeService: ModelSchemeService
  ) {
    super(fb)
  }

  ngOnInit() {
    if (!this.isNew) {
      this.commands = [
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
    }
    else {
      this.currentEntity = new Scheme(0, 3);
    }
    super.ngOnInit();
  }

  /**
   * 初始化数据
   *
   *
   * @memberof FaultAlarmGroupEditComponent
   */
  initData(): any | Observable<any> | Promise<any> {

    this.formPatchValue(this.currentEntity);

  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }

  canSaveChange(blade: any): boolean {
    return this.hasChange() && !this.hasError();
  }

  exeReset(blade: any): void {
    return this.formGroup.reset(this.currentEntity);
  }

  canReset(blade: any): boolean {
    return this.hasChange();
  }

  /**
   * 创建表单
   *
   *
   * @memberof FaultAlarmGroupEditComponent
   */
  createForm() {
    this.formGroup = this.fromBuider.group({
      'schemeName': [this.currentEntity.schemeName, [
        Validators.required,
        Validators.maxLength(50),
      ], (control: FormControl): any => this.schemeNameAsnyValidator(control)
      ],
      'multipleValue': this.currentEntity.multipleValue,
      'defaultValue': this.currentEntity.defaultValue
    });
  }

  schemeNameAsnyValidator(control: FormControl) {
    if (!control.value || control.value == this.currentEntity.schemeName) {
      return Observable.of(null);
    }
    return this.schemeService.hasSchemeService(control.value, this.currentEntity.categoryId, this.currentEntity.schemeId)
      .map(res => res ? {exist: true} : null);
  }

  /**
   * 设置表单错误对象
   *
   *
   * @memberof FaultAlarmGroupEditComponent
   */
  setFormError(): void {
    this.formErrors = {
      'schemeName': '',
    };
  }

  /**
   * 设置表单验证信息
   *
   *
   * @memberof FaultAlarmGroupEditComponent
   */
  setValidationMessages(): void {
    this.validationMessages = {
      'schemeName': {
        'required': '名称不能为空。',
        'maxlength': '名称不能多于50个字符长度。',
        'exist': '名称已存在'
      }
    };
  }

  /**
   * 创建一个风机状态
   *
   *
   * @memberof FaultAlarmGroupEditComponent
   */
  onCreate() {
    if (!this.hasError()) {
      this.changeCurrent();

      this.schemeService.create(this.currentEntity)
        .then(res => {
          if (res) {
            if (this.formGroup.value.defaultValue) {
              if (this.parentEntity.defaultChecked) {
                this.modelSchemeService.update({
                  id: this.parentEntity.defaultChecked.id,
                  modelId: this.parentEntity.current.modelId,
                  schemeId: res.schemeId,
                }).then(res => {
                  if (res) this.upData()
                }).catch(err => {
                  console.log(err)
                })

              } else {
                this.modelSchemeService.create({
                  id: 0,
                  modelId: this.parentEntity.current.modelId,
                  schemeId: res.schemeId,
                }).then(res => {
                  if (res) this.upData()
                }).catch(err => {
                  console.log(err)
                })
              }
            } else {
              this.upData()
            }

          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  upData() {

    let parentContainerInstance = this.parentBlade.bladeContainerInstance;
    parentContainerInstance.refresh(this.parentEntity.current);
    this.bladeService.closeBlade(this.currentBlade);
  }

  /**
   *
   *
   * @returns {(any | Promise<any> | Observable<any>)}
   * @memberof FaultAlarmGroupEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {

    if (this.canSaveChange(this.currentBlade)) {
      this.changeCurrent();

      return this.schemeService.update(this.currentEntity)
        .then(res => {
          if (res) {
            if (this.currentEntity.defaultValue != this.formGroup.value.defaultValue) {
              if (this.parentEntity.defaultChecked) {
                if (this.currentEntity.defaultValue && !this.formGroup.value.defaultValue) {
                  this.modelSchemeService.delete(this.parentEntity.defaultChecked.id)
                    .then(res => {
                      if (res) {
                        this.upData()
                      }
                    })
                    .catch(err => {
                      console.log(err)
                    });

                } else {
                  this.modelSchemeService.update({
                    id: this.parentEntity.defaultChecked.id,
                    modelId: this.parentEntity.current.modelId,
                    schemeId: this.currentEntity.schemeId,
                  }).then(res => {
                    if (res) this.upData()
                  }).catch(err => {
                    console.log(err)
                  })
                }
              } else {
                this.modelSchemeService.create({
                  id: 0,
                  modelId: this.parentEntity.current.modelId,
                  schemeId: this.currentEntity.schemeId,
                }).then(res => {
                  if (res) this.upData()
                }).catch(err => {
                  console.log(err)
                })
              }
            } else {
              this.upData()
            }


            return true;
          }
          throw new Error('数据更新失败！')
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  changeCurrent() {
    this.bladeData.isLoading = true;
    let formValue = this.formGroup.value as Scheme;
    this.currentEntity.schemeName = formValue.schemeName;
    this.currentEntity.multipleValue = formValue.multipleValue ? true : false;
  }
}


// WEBPACK FOOTER //
// ./src/app/module/basic/model/fault-alarm/fault-alarm-group-edit/fault-alarm-group-edit.component.ts
